package com.demoworld.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.lang.reflect.Method;

@Aspect
public class LogInAndOutAspect {
    public LogInAndOutAspect() {
        System.out.println("LogInAndOutAspect init");
    }

    @Around(value = "execution(* com.demoworld.web.controllers.*.*(..)) && @annotation(loggable)")
    public Object around(ProceedingJoinPoint joinPoint, LogInAndOutAspectable loggable) throws Throwable {
        return _around(joinPoint, loggable);
    }

    @Around(value = "execution(* com.demoworld.services.proxy.*.*(..)) && @annotation(loggable)")
    public Object around1(ProceedingJoinPoint joinPoint, LogInAndOutAspectable loggable) throws Throwable {
        return _around(joinPoint, loggable);
    }

    public Object _around(ProceedingJoinPoint joinPoint, LogInAndOutAspectable loggable) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        long start = System.currentTimeMillis();
        Object result = null;
        Exception e = null;
        try {
            result = joinPoint.proceed();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            long end = System.currentTimeMillis();
            System.out.println(String.format("class=%s, 方法=%s, 耗时=%d", loggable.clazzName().getName(), method.getName(), end - start));
        }

        String str = JsonUtil.toJson(joinPoint.getTarget());
        System.out.println(str);
        return result;
    }
}